import configparser
import sys
from datetime import time
import time
from typing import Dict, Any
import jwt
from flask import Blueprint
from flask import jsonify, request, abort, make_response, render_template
import hashlib
from tools.conf.confU import confU


from mongo.MongoHelper import MongoHelper

# 创建一个Blueprint的实例
print(__name__)
login = Blueprint('login', __name__)
database = confU().config.get('db', 'database')
myUrl = confU().config.get('db', 'url')
mongoHelper = MongoHelper(url=myUrl, database=database)
@login.route('/l')
def index():
    return jsonify({'message': 'Hello from my_api!'})

@login.route('/login', methods=['POST'])
def signin():
    '''
    -u是对应authorization -d 对应的是application/json
    curl -vvv -u admin:password -X POST -H "Content-Type: application/json" -d '{"username":"user", "password":"pass"}' http://localhost:6000/login
    '''
    auth = request.authorization
    print(request.json.get("username"))
    password = request.json.get("password")
    username = request.json.get("username")
    encrypted = None
    if username is None or password is None or (auth and auth.password is None) or (auth and auth.username is None):
        return make_response()
    else:
        m = hashlib.md5()
        m.update(password.encode("utf-8"))
        print(m.hexdigest())
        encrypted = m.hexdigest()

    if encrypted is not None:
        coll = mongoHelper.mongo_db.get_collection('sysUsers')
        qCon: dict[str, Any] = {'username': request.json.get("username"), 'password': encrypted,'status': 'Y'}
        res = coll.find_one(qCon)
        if res is not None:
            print(int(time.time()) + 3600 * 24 * 3)

            token = jwt.encode({
                'user': username,
                'id': str(res['_id']),
                'exp': int(time.time()) + 3600 * 24 * 3
            }, confU.config.get('encrypt', 'SECRET_KEY'), algorithm="HS256")

            return jsonify({'token': token, 'username': username, 'password': password, 'role': 'admin', 'roleId':1, 'permissions': ['*.*.*']})
        else:
            print()
    return make_response('Could not verify!', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})